function checkEnd(str1,str2){
     if(str2==null||str2==""||str1.length==0||str2.length>str1.length)
        return false;
     return str1.substring(str1.length-str2.length)==str2;

    }

    function checkStart(str1,str2){
     if(str2==null||str2==""||str1.length==0||str2.length>str1.length)
      return false;
     return str1.substr(0, str2.length) == str2;
    }

function isEmpty(s)
{
    return ((s == null) || (s.length == 0));
}

function isDigit(c)
{
    return ((c >= "0") && (c <= "9"))
}

function isInteger(s)
{
    if (isEmpty(s)) return true;
    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (!isDigit(c))
            return false;
    }
    return true;
}

function isLeapYear(year) {
    if (year % 400 == 0) return true;
    return (year % 4 == 0) && (year % 100 != 0);
}

function maxDayOfMonth(month, year) {
    var DAYS = new Array(12);
    DAYS[0] = 31;
    //Jan
    DAYS[1] = isLeapYear(year) ? 29 : 28;
    //Feb
    DAYS[2] = 31;
    //Mar
    DAYS[3] = 30;
    //Apr
    DAYS[4] = 31;
    //May
    DAYS[5] = 30;
    //Jun
    DAYS[6] = 31;
    //Jul
    DAYS[7] = 31;
    //Aug
    DAYS[8] = 30;
    //Sep
    DAYS[9] = 31;
    //Oct
    DAYS[10] = 30;
    //Nov
    DAYS[11] = 31;
    //Dec

    return DAYS[month - 1];
}

function isValidDate_DDMMYYYY(sDate) {
    // format check
    var bValid = true;
    // DD-MM-YYYY
    var regExp = /^(\d{2})\-(\d{2})\-(\d{4})$/;
    var regExp2 = /^(\d{2})\/(\d{2})\/(\d{4})$/;

    var sResult = regExp.exec(sDate);
    var sResult2 = regExp2.exec(sDate);

    if ((sResult == null) && (sResult2 == null)) {
        bValid = false;
    }

    if (!bValid) {
        return false;
    }

    var dd = sDate.substr(0, 2);
    var mm = sDate.substr(3, 2);
    var yyyy = sDate.substr(6, 4);

    if (1 > parseInt(mm, 10) || parseInt(mm, 10) > 12)  return false;
    return parseInt(dd, 10) <= maxDayOfMonth(mm, yyyy) && parseInt(dd, 10) > 0;
}

function convertDateFromStringToDate(sDate) {
    if (!isValidDate_DDMMYYYY(sDate))return null;
    var dd = sDate.substr(0, 2);
    var MM = sDate.substr(3, 2);
    var yyyy = sDate.substr(6, 4);
    var indd = dd.charAt(0) != '0' ? parseInt(dd, 10) : parseInt(dd.substr(1, 1), 10);
    var inMM = MM.charAt(0) != '0' ? parseInt(MM, 10) : parseInt(MM.substr(1, 1), 10);
    var inyyyy = parseInt(yyyy, 10);
    return new Date(inyyyy, inMM - 1, indd, 0, 0, 0, 0);
}

function compare2DatesValues(date1, date2) {
    if (date1 < date2) {
        return -1;
    } else if (date1 > date2) {
        return 1;
    } else {
        return 0;
    }
}

// Compare two input dates.
// If date1 is earlier than date2, return -1;
// If date1 is equal to date2, return 0;
// If date1 is laterer than date2, return 1;
function compare2Dates(date1, date2) {
    if (typeof(date1) == 'string' && typeof(date2) == 'string') {
        return compare2DatesValues(convertDateFromStringToDate(date1), convertDateFromStringToDate(date2));
    } else if (typeof(date1) == 'string' && date2 instanceof Date) {
        return compare2DatesValues(convertDateFromStringToDate(date1), date2);
    } else if (date1 instanceof Date && typeof(date2) == 'string') {
        return compare2DatesValues(date1, convertDateFromStringToDate(date2));
    }
    return compare2DatesValues(date1, date2);
}

function addError(e, errorText) {
    if (errorText.startsWith("[") || errorText.startsWith("]")) errorText = errorText.substr(1);
    if (errorText.endsWith("[") || errorText.endsWith("]")) errorText = errorText.substr(0, errorText.length - 1);
    if (typeof(e) == 'string') {
        var l = document.getElementsByName(e)[0];
        addErrorXHTML(l, errorText);
    } else {
        addErrorXHTML(e, errorText);
    }
}

function addErrorXHTML(e, errorText) {
    var newdiv = document.createElement("div");
    newdiv.id="errorMessages";
    newdiv.className="error";
    var contetxpath=document.getElementById("currentContextPath");
    var imagePath=contetxpath.value+"/images/iconWarning.gif";
    newdiv.innerHTML = "<img src="+imagePath+">" + errorText;
    for (var i = 0; i < e.parentNode.childNodes.length; i++) {
        if (e.parentNode.childNodes[i].id == "errorMessages") {
            e.parentNode.removeChild(e.parentNode.childNodes[i]);
        }
    }
    e.parentNode.appendChild(newdiv);
}

function addTopError(e, errorText){
	var l = document.getElementById(e);
	var newdiv = document.createElement("div");
    newdiv.id="errorMessages";
    newdiv.className="error";
	newdiv.innerHTML = '<img src="../images/iconWarning.gif">' + errorText;
	console.log(l);
	if (l.hasChildNodes()) {
        l.removeChild();
    }
	l.appendChild(newdiv);
}

function clearErrorMessages() {
    clearErrorMessagesXHTML();
}

function clearAllMessages(){
	clearErrorMessagesXHTML();
	clearSuccessMessagesXHTML();
}

function clearErrorMessagesXHTML() {
    while (document.getElementById("errorMessages")) {
        document.getElementById("errorMessages").parentNode.removeChild(document.getElementById("errorMessages"));
    }
}

function clearSuccessMessagesXHTML() {
    while (document.getElementById("successMessages")) {
        document.getElementById("successMessages").parentNode.removeChild(document.getElementById("successMessages"));
    }
}

/*  add action error message   */
function addActionError(errorText){
     var divMsg = document.getElementById("jsErrorMessages");
     if(divMsg != null){
        divMsg.className="txtActionError";
		 var contetxpath=document.getElementById("currentContextPath");
		 var imagePath=contetxpath.value+"/images/iconWarning.gif";
		 if(divMsg.innerHTML != '') divMsg.innerHTML = divMsg.innerHTML+"<br>";
		 divMsg.innerHTML =divMsg.innerHTML+"<img src="+imagePath+"> "+errorText;	
     }
}
/*  clear the message content of action   */
function clearActionMessages(){
	var divActionError = document.getElementById("errorMessages");
	var divJsError = document.getElementById("jsErrorMessages");
	if(divActionError != null){
		divActionError.innerHTML='';
		divActionError.className="";
	}
	if(divJsError != null){
		divJsError.innerHTML='';
        divJsError.className=";"
	}
}

//validation start

//required

function validateForm_required(field) {
    return field.value != null && field.value.trim() != "";
}

function validate_required(formName, fieldName) {
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return field.value != null && field.value.trim() != "";
}


function validateForm_int(field)
{
    if (isEmpty(field.value)) return true;
    return isInteger(field.value);
}

function validate_int(formName, fieldName)
{
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return validateForm_int(field);
}

function validateForm_number(field)
{
    if (isEmpty(field.value)) return true;
    return !isNaN(field.value);
}


function validate_number(formName, fieldName)
{
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return validateForm_number(field);
}

function validateForm_money(field,len, precision)
{
    if (isEmpty(field.value)) return true;
        len = len || 10;
    precision = precision || 2;
    var number =field.value;
    number=number.trim();

    var isMoney = new RegExp(/^(\-?|\+?)((\d{1,3}((,\d{3})*))|(\d+))((\.\d+){0,1})$/);
    var result = isMoney.test(number);

    if (!result) {
        return false;
    }

    number = number.replace(/,/g, '');

    var num_pieces = number.split(".");

    // Generic number check
    if ((number == "") || (number < 0) || (isNaN(parseFloat(number)))) {
        //alert("This is not a valid number.");
        return false;
    }

    // Check decimal count
    if (num_pieces.length > 2) {
        //alert("There are too many decimals in your number.");
        return false;
    }

    // Check initial length
    if (num_pieces[0].length > len) {
        //alert("This number is too large!");
        return false;
    }

    // Check decimal places
    if ((num_pieces.length == 2) && (num_pieces[1].length > precision)) {
        //alert("This number has too many decimal places or whitespaces.");
        return false;
    }

    return result;
}

function validate_money(formName, fieldName)
{
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return validateForm_number(field);
}



function validateForm_date(field)
{
    if (isEmpty(field.value)) return true;
    return isValidDate_DDMMYYYY(field.value);
}

function validate_date(formName, fieldName)
{
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return validateForm_date(field);
}

function validateForm_numberRange(field, iMinValue, iMaxValue)
{
    if (isEmpty(field.value)) return true;
    if (isNaN(field.value)) return false;
    return parseFloat(iMinValue, 10) <= parseFloat(field.value, 10) && parseFloat(field.value, 10) <= parseFloat(iMaxValue, 10);
}

function validate_numberRange(formName, fieldName, iMinValue, iMaxValue)
{
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    if (isNaN(field.value)) return false;
    return validateForm_numberRange(field, iMinValue, iMaxValue);
}

function validateForm_stringLength(field, iMinLen, iMaxLen) {
    if (isEmpty(field.value)) return true;
    return parseInt(iMinLen) <= field.value.length && field.value.length <= parseInt(iMaxLen);
}

function validate_stringLength(formName, fieldName, iMinLen, iMaxLen) {
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return validateForm_stringLength(field, iMinLen, iMaxLen);
}

function validateForm_email(emailStr) {
    emailStr = emailStr.value;
    return validateEmail(emailStr);
}

function validateEmail(emailValue) {
    if (emailValue == null || emailValue == "" || emailValue.length == 0) {
        return true;
    }
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailValue.match(emailPat);
    if (matchArray == null) {
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];
    if (user.match(userPat) == null) {
        return false;
    }
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return false;
            }
        }
        return true;
    }
    var domainArray = domain.match(domainPat);
    if (domainArray == null) {
        return false;
    }
    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    if ((domArr[domArr.length - 1].length < 2) ||
        (domArr[domArr.length - 1].length > 3)) {
        return false;
    }
    return len >= 2;
}

function validate_email(formName, fieldName) {
    var form = document.forms[formName];
    var field = form.elements[fieldName];
    return validateForm_email(field);
}

//validation end

/*
functionality: This function is used to validate a time.
arg0: time (HH:MM:SS)
*/
function isValidTime_HHMMSS(sTime) {
	// format check
	var bValid = true;
	// HH:MM:SS
	var regExp = /(\d{2}):(\d{2}):(\d{2})/;
	var sResult = regExp.exec(sTime);
	//alert(sResult);
	if(sResult == null) {
		bValid = false;
	}
	//alert(bValid);
	if(!bValid) {
		return false;
	}

	// range check
	hh = sTime.substr(0 , 2);
	mm = sTime.substr(3 , 2);
	ss = sTime.substr(6 , 2);
	//alert("hh="+hh+";mm="+mm+";ss="+ss);

	if(!(0 <= parseInt(hh , 10) && parseInt(hh , 10) <= 23)) {
		//alert("Invalid hour.");
		return false;
	}

	if(!(0 <= parseInt(mm , 10) && parseInt(mm , 10) <= 59)) {
		//alert("Invalid minute.");
		return false;
	}

	if(!(0 <= parseInt(ss , 10) && parseInt(ss , 10) <= 59)) {
		//alert("Invalid seconds.");
		return false;
	}

	return true;
}


function validationMonitorForm(prefix){
    $("td").removeClass("showErrorClass");
        var check=true;
        $("input:text,textarea", document.forms[0]).each(function(){
            if(check){
                if(isEmpty(this.value)){
                    if((this.id.indexOf("f_file")==-1)){
                        this.focus();
                        $(this).parents("tr:first").find("td:first").addClass("showErrorClass");
                        alert(prefix+$(this).parents("tr:first").find("td:first").text());
                        check=false;       
                    }
                }else{

                    if((this.id.indexOf("f_file")!=-1)){
                        if(checkEnd(this.value.toUpperCase(),".BAT")||checkEnd(this.value.toUpperCase(),".EXT")){
                            $(this).parents("tr:first").find("td:first").addClass("showErrorClass");
                            alert("\u4e0a\u4f20\u6587\u4ef6\u683c\u5f0f\u9519\u8bef");
                            check=false;
                        }
                    }
                }
            }
        }
    );
    return check;

}

function validateJqueryDate(object,suffix){
    if(!validateForm_date(document.getElementById($(object).prev("input:text").attr("id")))){
                            $(object).prev("input:text").focus();
                            $(object).parents("tr:first").find("td:first").addClass("showErrorClass");
                            alert($(object).parents("tr:first").find("td:first").text()+suffix);
        return false;
    }
    return true;
}






